<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>购票</title>
    <link rel="stylesheet" href="static/elementui.css">
    <script src="static/vue@2.6.14.js"></script>
    <script src="static/elementui.js"></script>
    <script src="static/axios.min.js"></script>
    <style>
        body {
            padding: 20px;
            font-family: Arial, sans-serif;
        }

        .card-container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-top: 20px;
        }

        .showtime-card {
            width: 300px;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            cursor: pointer;
            transition: transform 0.3s ease;
        }

        .showtime-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
        }

        .showtime-card img {
            width: 100%;
            height: auto;
            border-radius: 5px;
            margin-bottom: 10px;
        }

        .showtime-card h3 {
            margin: 10px 0;
            color: #333;
            font-size: 18px;
        }

        .showtime-card p {
            margin: 5px 0;
            color: #666;
            font-size: 14px;
        }

        .seat-selection {
            max-width: 800px;
            margin: 30px auto;
            padding: 20px;
            background: #f5f7fa;
            border-radius: 8px;
        }

        .screen {
            width: 80%;
            height: 30px;
            background: #d3dce6;
            margin: 0 auto 40px;
            text-align: center;
            line-height: 30px;
            border-radius: 5px;
            color: #5a5e66;
            font-size: 14px;
        }

        .seat-row {
            display: flex;
            justify-content: center;
            margin-bottom: 10px;
            gap: 10px;
        }

        .seat {
            width: 35px;
            height: 35px;
            line-height: 35px;
            text-align: center;
            border: 1px solid #ddd;
            cursor: pointer;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #67c23a;
            color: white;
            transition: all 0.3s ease;
        }

        .seat.selected {
            background-color: #f56c6c;
            transform: scale(1.1);
            cursor: not-allowed;
        }

        .seat.available {
            background-color: #67c23a;
        }

        .seat.sold {
            background-color: #909399;
            cursor: not-allowed;
            opacity: 0.7;
        }

        .seat i {
            font-size: 16px;
        }

        .seat-legend {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 30px;
            padding: 15px;
            background: white;
            border-radius: 5px;
        }

        .legend-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: #606266;
        }

        .legend-color {
            width: 20px;
            height: 20px;
            border-radius: 4px;
        }

        .price-info {
            text-align: center;
            margin-top: 20px;
            padding: 15px;
            background: white;
            border-radius: 5px;
            font-size: 16px;
            color: #303133;
        }

        .search-section {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .el-pagination {
            margin-top: 20px;
            text-align: center;
        }
    </style>
</head>
<body>
<div id="app">
    <div class="search-section">
        <el-input
                placeholder="搜索电影名称"
                v-model="searchKeyword"
                prefix-icon="el-icon-search"
                style="width: 300px;">
        </el-input>
        <el-button type="primary" @click="fetchShowtimes">搜索</el-button>
    </div>

    <div class="card-container">
        <div v-for="showtime in showtimes"
             :key="showtime.id"
             class="showtime-card"
             @click="handleShowtimeClick(showtime)">
            <img :src="showtime.movie.poster" :alt="showtime.movie.title">
            <h3>{{ showtime.movie.title }}</h3>
            <p><i class="el-icon-film"></i> <strong>影厅:</strong> {{ showtime.hall.name }}</p>
            <p><i class="el-icon-time"></i> <strong>开始时间:</strong> {{ showtime.startTime }}</p>
            <p><i class="el-icon-timer"></i> <strong>结束时间:</strong> {{ showtime.endTime }}</p>
            <p><i class="el-icon-money"></i> <strong>价格:</strong> ¥{{ showtime.price }}</p>
        </div>
    </div>

    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalShowtimes">
    </el-pagination>

    <el-dialog
            :title="currentShowtime.movie ? currentShowtime.movie.title + ' - 选座' : '选座'"
            :visible.sync="seatDialogVisible"
            width="80%"
            :before-close="handleDialogClose">
        <div v-if="currentShowtime.seatsLayout" class="seat-selection">
            <div class="screen">银幕</div>

            <div v-for="(row, rowIndex) in currentShowtime.seatsLayout"
                 :key="rowIndex"
                 class="seat-row">
                <div v-for="(seat, seatIndex) in row"
                     :key="seatIndex"
                     class="seat"
                     :class="{
                         'selected': isSelectedSeat(rowIndex, seatIndex),
                         'available': isAvailableSeat(rowIndex, seatIndex),
                         'sold': seat.sold
                     }"
                     @click="toggleSeatSelection(rowIndex, seatIndex)">
                    <i class="el-icon-potato-strips"></i>
                </div>
            </div>

            <div class="seat-legend">
                <div class="legend-item">
                    <div class="legend-color" style="background-color: #67c23a;"></div>
                    <span>可选座位</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color" style="background-color: #f56c6c;"></div>
                    <span>已选座位</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color" style="background-color: #909399;"></div>
                    <span>已售座位</span>
                </div>
            </div>

            <div class="price-info">
                <p>已选择 {{ selectedSeats.length }} 个座位</p>
                <p>总价: ¥{{ totalPrice }}</p>
            </div>
        </div>
        <span v-else>加载座位图失败，请重试</span>

        <div slot="footer" class="dialog-footer">
            <el-button @click="cancelSelection">取消选座</el-button>
            <el-button type="primary" @click="handlePlaceOrder" :disabled="selectedSeats.length === 0">
                确认购买
            </el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                searchKeyword: '',
                showtimes: [],
                totalShowtimes: 0,
                pageSize: 5,
                currentPage: 1,
                seatDialogVisible: false,
                currentShowtime: {},
                selectedSeats: [],
                loading: false
            };
        },
        computed: {
            totalPrice() {
                return this.selectedSeats.length * (this.currentShowtime.price || 0);
            }
        },
        watch: {
            searchKeyword(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.currentPage = 1;
                    this.fetchShowtimes();
                }
            }
        },
        methods: {
            fetchShowtimes() {
                this.loading = true;
                axios.get('/showtime?operation=findShowtimesByPageAndMovieId', {
                    params: {
                        keyword: this.searchKeyword,
                        pageNum: this.currentPage,
                        pageSize: this.pageSize
                    }
                }).then(response => {
                    const {code, data} = response.data;
                    if (code === 200) {
                        this.showtimes = data.data;
                        this.totalShowtimes = data.total;
                    } else {
                        this.$message.error('获取上映列表失败');
                    }
                }).catch(error => {
                    console.error('获取上映列表失败:', error);
                    this.$message.error('获取上映列表失败');
                }).finally(() => {
                    this.loading = false;
                });
            },

            handleShowtimeClick(showtime) {
                this.currentShowtime = Object.assign({}, showtime);
                try {
                    this.currentShowtime.seatsLayout = JSON.parse(showtime.hall.seatsLayout).map(row =>
                        row.map(seat => ({...seat, selected: false, sold: false}))
                    );

                    // 回显已售出座位
                    const soldSeats = JSON.parse(showtime.status || '[]');
                    soldSeats.forEach(seat => {
                        if (this.currentShowtime.seatsLayout[seat.row - 1]?.[seat.col - 1]) {
                            this.currentShowtime.seatsLayout[seat.row - 1][seat.col - 1].sold = true;
                        }
                    });

                    this.selectedSeats = [];
                    this.seatDialogVisible = true;
                } catch (error) {
                    console.error('解析座位布局失败:', error);
                    this.$message.error('座位布局加载失败');
                }
            },

            isSelectedSeat(rowIndex, seatIndex) {
                return this.selectedSeats.some(seat =>
                    seat.row === rowIndex + 1 && seat.col === seatIndex + 1
                );
            },

            isAvailableSeat(rowIndex, seatIndex) {
                const seat = this.currentShowtime.seatsLayout[rowIndex][seatIndex];
                return !seat.sold && !this.isSelectedSeat(rowIndex, seatIndex);
            },

            toggleSeatSelection(rowIndex, seatIndex) {
                const seat = this.currentShowtime.seatsLayout[rowIndex][seatIndex];
                if (seat.sold) {
                    return;
                }

                const seatInfo = {row: rowIndex + 1, col: seatIndex + 1};
                const selectedIndex = this.selectedSeats.findIndex(s =>
                    s.row === seatInfo.row && s.col === seatInfo.col
                );

                if (selectedIndex === -1) {
                    this.selectedSeats.push(seatInfo);
                } else {
                    this.selectedSeats.splice(selectedIndex, 1);
                }
            },

            handleSizeChange(val) {
                this.pageSize = val;
                this.fetchShowtimes();
            },

            handleCurrentChange(val) {
                this.currentPage = val;
                this.fetchShowtimes();
            },

            cancelSelection() {
                this.$confirm('确定要取消选座吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.selectedSeats = [];
                    this.seatDialogVisible = false;
                }).catch(() => {
                });
            },

            handleDialogClose(done) {
                if (this.selectedSeats.length > 0) {
                    this.cancelSelection();
                } else {
                    done();
                }
            },

            handlePlaceOrder() {
                const user = JSON.parse(localStorage.getItem('user'));
                if (!user) {
                    this.$message.error('请先登录');
                    return;
                }

                if (this.selectedSeats.length === 0) {
                    this.$message.warning('请至少选择一个座位');
                    return;
                }

                this.$confirm(`确认购买 ${this.selectedSeats.length} 个座位，总价 ¥${this.totalPrice}？`, '确认购买', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 创建订单对象
                    const order = {
                        userId: user.id,
                        showtimeId: this.currentShowtime.id,
                        seats: this.selectedSeats,
                        totalPrice: this.totalPrice,
                        orderTime: new Date().toISOString(),
                        status: JSON.stringify({
                            seats: this.selectedSeats,
                            paymentStatus: 'pending' // 支付状态，可以是 'pending', 'paid', 'failed' 等
                        })
                    };

                    // 发送订单数据到后端
                    axios.post('/order?operation=addOrder', order)
                        .then(response => {
                            const { code, msg } = response.data;
                            if (code === 200) {
                                this.$message.success('购票成功！');
                                this.selectedSeats = [];
                                this.seatDialogVisible = false;
                                this.fetchShowtimes(); // 刷新上映列表

                                // 更新座位状态
                                this.selectedSeats.forEach(seat => {
                                    if (this.currentShowtime.seatsLayout[seat.row - 1]?.[seat.col - 1]) {
                                        this.currentShowtime.seatsLayout[seat.row - 1][seat.col - 1].sold = true;
                                    }
                                });

                                // 更新影片的 status
                                const updatedStatus = JSON.stringify(this.currentShowtime.seatsLayout.flat().filter(seat => seat.sold));
                                axios.post('/showtime?operation=updateShowtime', {
                                    id: this.currentShowtime.id,
                                    status: updatedStatus
                                }).then(response => {
                                    if (response.data.code === 200) {
                                        // this.$message.success('影片状态更新成功！');
                                    } else {
                                        this.$message.error('更新影片状态失败');
                                    }
                                }).catch(error => {
                                    console.error('更新影片状态失败:', error);
                                    this.$message.error('更新影片状态失败');
                                });
                            } else {
                                this.$message.error(msg || '购票失败');
                            }
                        })
                        .catch(error => {
                            console.error('购票失败:', error);
                            this.$message.error('购票失败');
                        });
                });
            },

            formatDateTime(datetime) {
                if (!datetime) return '';
                const date = new Date(datetime);
                const pad = (num) => num.toString().padStart(2, '0');
                return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
            },

            // 检查座位是否可选
            checkSeatAvailability(rowIndex, seatIndex) {
                const seat = this.currentShowtime.seatsLayout[rowIndex][seatIndex];
                if (!seat) return false;
                return !seat.sold && !this.isSelectedSeat(rowIndex, seatIndex);
            },

            // 获取座位标识
            getSeatLabel(rowIndex, seatIndex) {
                return `${rowIndex + 1}排${seatIndex + 1}号`;
            },

            // 检查用户登录状态
            checkLoginStatus() {
                const user = JSON.parse(localStorage.getItem('user'));
                if (!user) {
                    this.$message.warning('请先登录');
                    return false;
                }
                return true;
            },

            // 处理错误
            handleError(error, message = '操作失败') {
                console.error(error);
                this.$message.error(message);
            }
        },
        mounted() {
            this.fetchShowtimes();

            // 添加窗口关闭前的提示
            window.addEventListener('beforeunload', (event) => {
                if (this.selectedSeats.length > 0) {
                    event.preventDefault();
                    event.returnValue = '您有未完成的选座，确定要离开吗？';
                }
            });
        },
        beforeDestroy() {
            // 移除事件监听
            window.removeEventListener('beforeunload');
        }
    });
</script>
</body>
</html>